<template>
    <div class="manage">
        <div class="manage-header">
            <el-form :model="searchForm" :inline="true" label-width="90px">
                <el-form-item label="用户名/昵称">
                    <el-input v-model="searchForm.name" clearable size="small" placeholder="支持用户名或昵称"></el-input>
                </el-form-item>

                <el-form-item label="性别">
                    <el-select v-model="searchForm.gender" multiple size="small" placeholder="请选择">
                        <el-option v-for="(item, key) in genderMap" :key="key" :label="item" :value="key"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="状态">
                    <el-select v-model="searchForm.status" clearable size="small" placeholder="请选择">
                        <el-option label="正常" :value="1"></el-option>
                        <el-option label="冻结" :value="0"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="角色">
                    <el-select v-model="searchForm.role" size="small" multiple placeholder="请选择">
                        <el-option v-for="(item, key) in params.roles" :key="key" :label="item" :value="key"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="注册时间">
                    <el-date-picker
                        v-model="searchForm.date"
                        type="daterange"
                        size="small"
                        align="right"
                        unlink-panels
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd"
                        :picker-options="pickerOptions">
                    </el-date-picker>
                </el-form-item>

                <el-form-item>
                    <el-button v-if="params.canQuery" type="primary" size="small" @click="onSubmit">查询</el-button>
                    <el-button v-if="params.canAdd" type="primary" @click="add" size="small">新增</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="common-table">
            <el-table
                stripe
                height="90%"
                :data="tableData"
                style="width: 100%">
                <el-table-column
                    prop="name"
                    label="用户名"
                    width="180">
                </el-table-column>

                <el-table-column prop="nickname" label="昵称" width="180"></el-table-column>

                <el-table-column label="性别" width="130">
                    <template slot-scope="scope">
                        <span style="margin-left: 10px">{{ genderMap[scope.row.gender] }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="状态" width="130">
                    <template slot-scope="scope">
                        <el-switch
                            active-color="#409EFF"
                            inactive-color="#F56C6C"
                            @change="handleStatus(scope.row)"
                            v-model="scope.row.status">
                        </el-switch>
                    </template>
                </el-table-column>

                <el-table-column prop="created_at" label="注册时间" width="180"></el-table-column>

                <el-table-column prop="role.label" label="角色">
                    <template slot-scope="scope">
                        <el-tag size="mini" type="success" effect="dark">
                            {{ scope.row.role !== null ? scope.row.role.label : '未分配' }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button v-if="scope.row.can_update" @click="handleEdit(scope.row)" type="primary" size="mini">编辑</el-button>
                        <el-button v-if="scope.row.can_delete" @click="handleDelete(scope.row)" type="danger" size="mini">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pager">
                <el-pagination
                    background
                    layout="prev, pager, next"
                    @current-change = "pageChanged"
                    :page-size="pageData.limit"
                    :current-page="pageData.page"
                    :total="total">
                </el-pagination>
            </div>
        </div>

        <el-dialog
            :title="typeof form.id === 'number' ? '编辑用户' : '新增用户'"
            :visible.sync="dialogVisible"
            @close="onClosed"
            :destroy-on-close="true"
            width="1200">
            <el-form ref="form" :model="form" :rules="rules" :inline="true"  label-width="100px">
                <el-form-item label="用户名" prop="name">
                    <el-input v-model="form.name" size="small" style="width: 200px" placeholder="请输入用户名"></el-input>
                </el-form-item>

                <el-form-item v-if="typeof form.id !== 'number'" label="密码" prop="password">
                    <el-input type="password" v-model="form.password" size="small" style="width: 200px" placeholder="请输入密码"></el-input>
                </el-form-item>

                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="form.nickname" size="small" style="width: 200px" placeholder="请输入昵称"></el-input>
                </el-form-item>

                <el-form-item label="性别" prop="gender">
                    <el-select v-model="form.gender" size="small" style="width: 200px" placeholder="请选择">
                        <el-option v-for="(item, key) in genderMap" :key="key" :label="item" :value="parseInt(key)"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item v-if="params.isAdmin" label="角色" prop="role">
                    <el-select v-model="form.role" size="small" style="width: 200px" placeholder="请选择">
                        <el-option v-for="(item, key) in params.roles" :key="key" :label="item" :value="parseInt(key)"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="简介" prop="description">
                    <el-input type="textarea" size="small" style="width: 510px" :rows="3" v-model="form.description" placeholder="请输入简介"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="dialogVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="handleUser">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>

import {getUserList, addUser, editUser, deleteUser, statusUser, getInit} from "@/api/user"

export default {
    data() {
        return {
            dialogVisible: false,
            form: {
                id: '',
                name: '',
                password: '',
                nickname: '',
                gender: '',
                role: '',
                description: ''
            },
            genderMap: {
                "1": "男",
                "2": "女",
                "3": "未设置",
            },
            params: {
                roles: {},
                isAdmin: false,
                canQuery: false,
                canAdd: false
            },
            searchForm: {
                name: '',
                gender: [],
                status: '',
                role: [],
                date: []
            },
            tableData: [],
            total: 0,
            pageData: {
                page: 1,
                limit: 10
            },
            rules: {
                name: [
                    { required: true, message: '请输入用户名', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
                ],
                nickname: [
                    { required: true, message: '请输入昵称', trigger: 'blur' }
                ],
                gender: [
                    { required: true, message: '请选择性别', trigger: 'change' }
                ],
                role: [
                    { required: true, message: '请选择角色', trigger: 'change' }
                ]
            },
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            }
        }
    },
    created() {
        this.getInit()
        this.getList()
    },
    methods: {
        getInit() {
            getInit().then(({ data }) => {
                this.params = data.data
                console.log(this.params)
            })
        },
        getList() {
            getUserList({params: {...this.pageData, ...this.searchForm}}).then(({ data }) => {
                console.log(data)
                this.tableData = data.data
                this.total = data.meta.total || 0
            })
        },
        add() {
            this.dialogVisible = true
            this.form.id = ''
        },
        handleUser() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    if (this.form.id) {
                        editUser(this.form.id, this.form).then(({ data }) => {
                            if (data.code === 200) {
                                this.$message.success('编辑用户成功')
                            } else {
                                this.$message.error(data.data)
                            }
                        })
                    } else {
                        addUser(this.form).then(({ data }) => {
                            if (data.code === 201) {
                                this.$message.success(data.data)
                            } else {
                                this.$message.error(data.data)
                            }
                        })
                    }

                    this.$refs.form.resetFields()
                    this.getList()
                    this.dialogVisible = false
                }
            })
        },
        handleEdit(row) {
            this.form = JSON.parse(JSON.stringify(row))
            this.form.role = row.role !== null ? row.role.id : ''
            this.dialogVisible = true
        },
        handleStatus(row) {
            statusUser(row.id).then(({ data }) => {
                if (data.code === 200) {
                    row.status = data.data.status
                }
            })
        },
        handleDelete(row) {
            this.$confirm('确认要删除该用户吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteUser(row.id).then(({ data }) => {
                    // console.log(data)
                    if (data.code === 200) {
                        this.$message.success(data.data)
                    } else {
                        this.$message.error(data.data)
                    }
                    this.getList()
                })
            }).catch(() => {

            })
        },
        pageChanged(val) {
            this.pageData.page = val
            this.getList()
        },
        // 对话框关闭的回调
        onClosed() {
            this.$refs.form.resetFields()
            Object.assign(this.form, this.$options.data().form)
        },
        onSubmit() {
            this.pageData.page = 1
            this.getList()
        }
    }
}
</script>

<style lang="less" scoped>
.manage {
    height: 90%;

    .manage-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .el-form {
            border: 1px solid #eee;
            border-radius: 5px;
            padding: 10px 0 0 10px;
            margin-bottom: 15px;
        }
    }

    .common-table {
        height: calc(100% - 62px);
        position: relative;

        .el-table::before {
            height: 0;
        }

        /deep/.el-table__header-wrapper {
            .cell {
                font-weight: normal;
                color: #666666;
            }
        }

        .pager {
            position: absolute;
            bottom: 0;
            right: 20px;
        }
    }
}
</style>
